import React ,{useState,useRef}from 'react'
import style from './Search.module.scss'

import axios, { all } from 'axios'
import { useNavigate } from 'react-router-dom'
const Urls = [
  'https://zyxcl.xyz/exam_api/zh',
  'https://zyxcl.xyz/exam_api/xl',
  'https://zyxcl.xyz/exam_api/sx'
]

const getApi = async keyWords => {

  const res = await Promise.all(Urls.map(item => axios.get(item)))
  const allList = res.map(it => it.data.items).flat()
  const curItem = []
  allList.forEach(item => {
    if(item.title.includes(keyWords) && !curItem.find(v => v.item_id === item.item_id)){
      curItem.push(item)
    }
  })

  return curItem
}


const Search = () => {
  const [list,setList] = useState([])
  const navigate = useNavigate()
  const timer = useRef(null)

  const changeVal = async (e) => {
    if(timer.current) clearTimeout(timer.current)
    timer.current = setTimeout(async () => {
      const res = await getApi(e.target.value)
      const newList = res.map(item => {
        return {
          ...item,
          title:item.title.replaceAll(e.target.value,`<span style="color:red">${e.target.value}</span>`)
        }
      })
      console.log(newList)
      setList(newList)
    },800)
  }


  return (
    <div className={style.head}>
      <header>
        <input type="text" placeholder='请输入商品名称' onChange={changeVal}/>
      </header>
      <ul className={style.list}>
        {list.map(item => 
          <li key={item.item_id} dangerouslySetInnerHTML={{__html:item.title}}
            onClick={() => navigate(`/detail?id=${item.item_id}`)}
          ></li>
        )}
      </ul>
    </div>
  )
}

export default Search